package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Category;
import com.jiawa.wiki.domain.CategoryExample;
import com.jiawa.wiki.mapper.CategoryMapper;
import com.jiawa.wiki.req.CategoryQueryReq;
import com.jiawa.wiki.req.CategorySaveReq;
import com.jiawa.wiki.resp.CategoryQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryService {

    @Resource
    public CategoryMapper categoryMapper;

    @Resource
    public SnowFlake snowFlake;

    private final static Logger LOG = LoggerFactory.getLogger(CategoryService.class);

    public PageResp<CategoryQueryResp> getlist(CategoryQueryReq req) {
        //ctrl+alt+v
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();


        PageHelper.startPage(req.getPage(), req.getSize());
        //直接从数据库中取出的数据
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        //ctrl+alt+v、
        //PageResp 类
        //pageResp 对象
        PageResp<CategoryQueryResp> pageResp = new PageResp<>();

        pageResp.setTotal(pageInfo.getTotal());

        pageResp.setList(list);

        return pageResp;

    }

    /*
     * @Description:一次性查出所有书
     * @param null
     * @return: null
     * @Author: wengyiting
     * @Date: 2024/5/31 下午 3:09
     */

    public List<CategoryQueryResp> all() {
        //ctrl+alt+v
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");

        //直接从数据库中取出的数据
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        return list;

    }


    //编辑
    public void save(CategorySaveReq req) {

        Category category = CopyUtil.copy(req, Category.class);

        if (!ObjectUtils.isEmpty(req.getId())) {
            //更新
            categoryMapper.updateByPrimaryKey(category);
        } else {
            //新增
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }
    }

    //删除
    public void delete(long id){
        categoryMapper.deleteByPrimaryKey(id);
    }


}